import {isRealNode} from "../../../core/vdom/utils";
import {hasOwn, isDef} from "../../../shared/util";
import {VIRTUAL_NODE_TYPE} from "../../../constant";

function updateAttr (oldNode, newNode) {

    if (newNode.nodeType !== VIRTUAL_NODE_TYPE.ELEMENT) {
        return;
    }

    let elem = null;
    let isOldNodeReal = false;
    if (isRealNode(oldNode)) {
        elem = oldNode;
        isOldNodeReal = true;
    }
    else {
        elem = newNode.elem;
    }

    if (isOldNodeReal) {
        // 绑定静态的属性
        const attrs = newNode.data.attrs;
        for (let name in attrs) {
            elem.setAttribute(name, attrs[name]);
        }
        // 绑定动态的属性
        if (isDef(newNode.data.bindAttrs)) {
            const bindAttrs = newNode.data.bindAttrs;
            for (let name in bindAttrs) {
                elem.setAttribute(name, bindAttrs[name]);
            }
        }
    }
    else {
        const oldBindAttrs = oldNode.data.bindAttrs;
        const newBindAttrs = newNode.data.bindAttrs;

        // 去除 newBindAttrs 中没有的旧属性
        for (let oldAttr in oldBindAttrs) {
            if (!hasOwn(newBindAttrs, oldAttr)) {
                elem.removeAttribute(oldAttr);
            }
        }
        // 添加或更新 newBindAttrs 中的新属性
        for (let newAttr in newBindAttrs) {
            if (!hasOwn(oldBindAttrs, newAttr)) {
                elem.setAttribute(newAttr, newBindAttrs[newAttr]);
            }
            else {
                const oldAttrValue = oldBindAttrs[newAttr];
                const newAttrValue = newBindAttrs[newAttr];
                if (oldAttrValue !== newAttrValue) {
                    elem.setAttribute(newAttr, newAttrValue);
                }
            }
        }
    }

}

export default {
    mount: updateAttr,
    update: updateAttr,
};
